<template>
	<div class="container">
		<cl-crud ref="crud" @load="onLoad">
			<template #slot-filter="{scope}">
				<!--平台-->
				<el-select
					size="mini"
					v-model="selects.union"
					placeholder="请选择阿里妈妈"
					filterable
					@change="
						val => {
							refresh({ taobaoId: val });
						}
					"
				>
					<el-option label="全部阿里妈妈" value></el-option>
					<el-option
						:label="item.account"
						:value="item.id"
						v-for="(item, index) in options.union"
						:key="index"
					></el-option>
				</el-select>
				<!--运营人-->
				<el-select
					size="mini"
					v-model="selects.staffId"
					placeholder="请选择运营人"
					filterable
					@change="
						val => {
							refresh({ staffId: val });
						}
					"
				>
					<el-option label="全部运营人" value></el-option>
					<el-option
						:label="item.username"
						:value="item.id"
						v-for="(item, index) in options.staff"
						:key="index"
					></el-option>
				</el-select>
				<!--标签-->
				<el-select
					size="mini"
					v-model="selects.label"
					placeholder="请选择标签"
					filterable
					@change="
						val => {
							refresh({ label: val });
						}
					"
				>
					<el-option label="全部标签" value></el-option>
					<el-option
						:label="item"
						:value="item"
						v-for="(item, index) in options.label"
						:key="index"
					></el-option>
				</el-select>
				<el-button
					@click="addStaff"
					:disabled="selectRow.length > 0 ? false : true"
					style="margin-left:10px"
					size="mini"
					type="primary"
					>绑定运营人</el-button
				>
			</template>
			<template #slot-add>
				<el-button style="margin-left:10px" size="mini" type="primary" @click="bindPid"
					>绑定推广位</el-button
				>
			</template>
			<template #slot-add-tag>
				<el-button
					style="margin-left:10px"
					size="mini"
					type="primary"
					@click="addLabels"
					:disabled="selectRow.length > 0 ? false : true"
					>批量添加标签</el-button
				>
				<!-- 显示不显示 -->
				<el-select
					size="mini"
					v-model="selects.display"
					filterable
					@change="
						val => {
							refresh({ display: val });
						}
					"
				>
					<el-option
						:label="item.label"
						:value="item.value"
						v-for="(item, index) in options.display"
						:key="index"
					></el-option>
				</el-select>
			</template>

			<template #table-column-label="{ scope }">
				<div class="label-list">
					<el-tag
						v-for="(item, index) in scope.row.labelList"
						:key="index"
						:disable-transitions="false"
						@close="removeLabel(scope.row, index)"
						size="small"
						style="margin: 4px"
						closable
						>{{ item }}</el-tag
					>
					<a
						class="add-label"
						@click="addLabel(scope.row)"
						v-if="scope.row.labelList && scope.row.labelList.length === 0"
						>添加标签</a
					>
					<i class="el-icon-plus" @click="addLabel(scope.row)" v-else></i>
				</div>
			</template>
			<template #slot-show="{ scope }">
				<span
					style="margin-left: 10px; color: #FF4400; cursor: pointer;"
					v-if="scope.row.display === 0"
					@click="changeShow(scope.row)"
					>显示</span
				>
				<span
					style="margin-left: 10px; color: #FF4400; cursor: pointer;"
					v-else
					@click="changeShow(scope.row)"
					>不显示</span
				>
			</template>
		</cl-crud>

		<!--创建标签弹窗-->
		<label-dig ref="label" :item="item" @refresh="refresh"></label-dig>
		<!-- 新增推广位 -->
		<cl-form ref="cl-form"></cl-form>
	</div>
</template>

<script>
import LabelDig from './components/label-dig';
export default {
	name: 'extension',
	components: {
		LabelDig
	},
	data() {
		return {
			selects: {
				label: null,
				display: 1
			},
			options: {
				union: [],
				staff: [],
				label: [],
				display: [
					{ label: '显示', value: 1 },
					{ label: '不显示', value: 0 }
				]
			},
			item: null, // 当前行
			selectRow: [] // 当前选中行
		};
	},
	created() {
		// 获取基础筛选数据
		this.getFilterList();
	},
	methods: {
		onLoad({ ctx, app }) {
			this.crud = app;
			ctx.service(this.$service.account.extension)
				.set('table', {
					columns: [
						{
							type: 'selection',
							label: '全选',
							align: 'center',
							width: '60px'
						},
						{
							prop: 'positionName',
							label: '账号名称',
							align: 'center',
							minWidth: 150
						},
						{
							prop: 'positionId',
							label: '推广位',
							align: 'center',
							minWidth: 150,
							emptyText: '无'
						},
						{
							prop: 'username',
							label: '运营人',
							align: 'center',
							minWidth: 150,
							emptyText: '无'
						},
						{
							prop: 'label',
							label: '标签',
							align: 'center',
							minWidth: 150
						}
					],

					props: {
						'default-sort': {
							prop: 'updateTime',
							// prop: 'positionName',
							order: 'descending'
						}
					},

					op: {
						layout: ['edit', 'slot-show']
					},
					on: {
						'selection-change': selection => {
							this.selectRow = selection;
						}
					}
				})
				.set('upsert', {
					props: {
						width: '500px',
						labelWidth: '100px'
					},
					items: [
						{
							prop: 'positionName',
							label: '账号名称：',
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请填写账号名称',
									clearable: true
								}
							},
							rules: {
								required: true,
								message: '名称不能为空'
							}
						},
						{
							prop: 'taobaoId',
							label: '来源联盟：',
							component: {
								name: 'el-select',
								options: [],
								props: {
									disabled: true
								}
							},
							rules: {
								required: true,
								message: '标识不能为空'
							}
						},
						{
							prop: 'staffId',
							label: '运营人：',
							value: '',
							component: {
								name: 'el-select',
								options: []
							},
							rules: {
								required: true,
								message: '运营人不能为空'
							}
						}
					]
				})
				.set('layout', [
					[
						'refresh-btn',
						'slot-filter',
						'slot-add',
						'slot-add-tag',
						'flex1',
						'search-key'
					],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('refresh', async (params, { next, render }) => {
					let { list } = await next(params);
					list.map(e => {
						e.labelList = e.label ? e.label.split(',') : [];
					});

					render(list);
				})
				.on('open', (isEdit, form) => {
					if (isEdit) {
						let staff = [
							{
								label: '无',
								value: '0'
							}
						];
						let staffFlag = 0;
						this.options.staff.forEach(item => {
							// 判断当前运营人员是否还在
							if (form.staffId === item.id) {
								staffFlag++;
							}
							staff.push({
								label: item.username,
								value: item.id
							});
						});

						if (staffFlag === 0) {
							app.setForm('staffId', '0');
						} else {
							app.setForm('staffId', form.staffId);
						}
						app.setData('upsert.items[prop:staffId].component.options', staff);

						let union = [];
						this.options.union.forEach(item => {
							union.push({
								label: item.account,
								value: item.id
							});
						});
						app.setData('upsert.items[prop:taobaoId].component.options', union);
					}
				})
				.done();

			app.refresh({ ...this.selects });
		},
		refresh(params) {
			this.crud.refresh(params);
			this.getFilterList();
		},
		// 修改是否显示
		changeShow(row) {
			let display = row.display;
			display ? (display = 0) : (display = 1);
			this.$service.account.extension
				.update({
					id: row.id,
					display: display
				})
				.then(() => {
					this.refresh();
				})
				.catch(err => {
					this.$message.error(err);
				});
		},
		// 批量绑定运营人
		addLabels() {
			let ids = '';
			this.selectRow.forEach(item => {
				ids = ids ? ids + ',' + item.id : item.id;
			});
			this.item = ids;
			this.$refs.label.open(this.options.label, true);
		},
		// 绑定PID
		bindPid() {
			this.$refs['cl-form'].open({
				props: {
					title: '绑定推广位',
					width: '500px',
					labelWidth: '120px'
				},
				items: [
					{
						prop: 'taobaoId',
						label: '选择联盟账号',
						value: '',
						component: {
							name: 'el-select',
							options: (() => {
								let options = [];
								this.options.union.forEach(item => {
									options.push({
										label: item.account,
										value: item.id
									});
								});
								return options;
							})()
						},
						rules: {
							required: true,
							message: '标识不能为空'
						}
					},
					{
						prop: 'positionId',
						label: '请输入推广位',
						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请填写推广位',
								clearable: true
							}
						},
						rules: {
							required: true,
							message: '推广位不能为空'
						}
					},
					{
						prop: 'positionName',
						label: '推广位名称',
						component: {
							name: 'el-input',
							attrs: {
								placeholder: '请填写推广位名称',
								clearable: true
							}
						}
					},
					{
						prop: 'staffId',
						label: '运营人',
						component: {
							name: 'el-select',
							options: (() => {
								let options = [];
								this.options.staff.forEach(item => {
									options.push({
										label: item.username,
										value: item.id
									});
								});
								return options;
							})()
						}
					}
				],
				on: {
					submit: ({ data, done, close }) => {
						console.log('dataaaa', data, done, close);
						this.$service.account.extension
							.bindPid(data)
							.then(() => {
								this.$message.success('绑定推广位成功');
								close();
								this.refresh();
							})
							.catch(error => {
								this.$message.error(error);
								done();
							});
					}
				}
			});
		},
		// 批量添加运营人
		addStaff() {
			// let messages = '';
			let ids = '';
			this.selectRow.forEach(item => {
				ids = ids ? ids + ',' + item.id : item.id;
				// if (item.username) {
				// 	messages =
				// 		messages + `<div>推广位:${item.positionName}:已绑定${item.username}</div>`;
				// }
			});
			// if (messages) {
			// 	this.$notify({
			// 		title: '有选中项已有运营人',
			// 		type: 'warning',
			// 		dangerouslyUseHTMLString: true,
			// 		message:
			// 			messages +
			// 			'<div style="color:#FF4400" >您可以不勾选已有运营人的推广位或者将运营人编辑为无</div>'
			// 	});
			// }
			this.$refs['cl-form'].open({
				props: {
					label: '绑定运营人',
					labelWidth: '100px',
					width: '400px',
					showClose: false
				},
				items: [
					{
						prop: 'staffId',
						label: '运营人：',
						value: '',
						component: {
							name: 'el-select',
							options: (() => {
								let options = [];
								this.options.staff.forEach(item => {
									options.push({
										label: item.username,
										value: item.id
									});
								});
								return options;
							})()
						},
						rules: {
							required: true,
							message: '运营人不能为空'
						}
					}
				],
				on: {
					submit: ({ data, done, close }) => {
						// 提交事件
						this.$service.account.extension
							.bindStaff({
								ids,
								staffId: data.staffId
							})
							.then(res => {
								console.log(res);
								this.$message({
									message: '添加成功',
									type: 'success'
								});
								this.crud.refresh();
								done();
								close();
							})
							.catch(err => this.$message.error(err));
					}
				}
			});
		},
		// 获取筛选下拉
		getFilterList() {
			this.getUnionList();
			this.getLabelList();
			this.getStaffList();
		},
		// 获取联盟账号
		getUnionList() {
			this.$service.account.union.list().then(res => {
				this.options.union = res;
			});
		},
		// 获取运营人列表
		getStaffList() {
			this.$service.account.extension.staffList().then(res => {
				this.options.staff = res;
			});
		},
		// 获取标签列表
		getLabelList() {
			this.$service.account.extension.labelList().then(res => {
				this.options.label = res;
			});
		},
		// 添加标签
		addLabel(item) {
			this.item = item;
			this.$refs.label.open(this.options.label, false);
		},
		// 删除标签
		removeLabel(obj, i) {
			let labelArr = obj.labelList.filter((item, index) => {
				if (index === i) {
					return false;
				}
				return true;
			});
			this.$service.account.extension
				.update({
					id: obj.id,
					label: labelArr.join(',')
				})
				.then(() => {
					this.$message.success('删除成功');
					this.refresh();
				})
				.catch(err => {
					this.$message.error(err);
				});
		}
	}
};
</script>

<style lang="stylus" scoped>
.container {
	i {
		cursor pointer
		transition .3s
		color $main-color
		margin-left 4px
		font-size 20px
		&:hover {
			opacity .8
		}
	}
	.el-select {
		margin-left 10px
	}
	.label-list {
		flexBox(center, center, row, wrap)
		.add-label {
			color $main-color
			cursor pointer
			transition .3s
			&:hover {
				opacity .8
			}
		}
		.el-icon-plus {
			font-size 14px
		}
	}
}
</style>
